package cn.zmwh.manage.admin.modules.upms.service;

import cn.hutool.core.collection.CollUtil;
import cn.zmwh.manage.admin.modules.upms.mapper.SysUserRoleMapper;
import cn.zmwh.manage.admin.modules.upms.pojo.entity.SysUserRole;
import cn.zmwh.manage.admin.modules.upms.pojo.request.UserRelevanceRequest;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 用户角色关系 服务实现类
 * </p>
 *
 * @author dmzmwh
 * @since 2025-03-11
 */
@Service
public class SysUserRoleService extends ServiceImpl<SysUserRoleMapper, SysUserRole> {

    public void delByRoleId(Integer roleId) {
        baseMapper.delete(Wrappers.<SysUserRole>lambdaQuery()
                .eq(SysUserRole::getRoleId, roleId));
    }

    public void relevance(UserRelevanceRequest request) {
        baseMapper.delete(Wrappers.<SysUserRole>lambdaQuery()
                .eq(SysUserRole::getUid, request.getUid()));
        if (CollUtil.isEmpty(request.getRoleIds())) {
            return;
        }
        for (Long roleId : request.getRoleIds()) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUid(request.getUid());
            sysUserRole.setRoleId(roleId);
            baseMapper.insert(sysUserRole);
        }
    }


    public void relevance(Long id, Set<Long> roleIds) {
        baseMapper.delete(Wrappers.<SysUserRole>lambdaQuery()
                .eq(SysUserRole::getRoleId, id));
        if (CollUtil.isEmpty(roleIds)) {
            return;
        }
        List<SysUserRole> lsit = new ArrayList<>();
        roleIds.forEach(ite -> {
            SysUserRole item = new SysUserRole();
            item.setUid(id);
            item.setRoleId(ite);
            item.setCreateTime(new Date());
            lsit.add(item);
        });
        saveBatch(lsit);
    }
}
